package com.lingeringdream.luciole.slice;

import com.lingeringdream.luciole.ResourceTable;
import com.lingeringdream.luciole.helper.ResourceHelper;
import com.lingeringdream.luciole.helper.navigation.NavigationItem;
import com.lingeringdream.luciole.slice.fraction.IndividualFraction;
import com.lingeringdream.luciole.slice.fraction.NewsFraction;
import com.lingeringdream.luciole.slice.fraction.ScanFraction;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.ability.fraction.Fraction;
import ohos.aafwk.ability.fraction.FractionAbility;
import ohos.aafwk.ability.fraction.FractionScheduler;
import ohos.aafwk.content.Intent;
import ohos.agp.components.*;
import ohos.agp.components.element.VectorElement;
import ohos.agp.utils.Color;
import ohos.agp.utils.Point;
import ohos.agp.window.service.DisplayManager;
import ohos.agp.window.service.WindowManager;
import ohos.hiviewdfx.HiLog;
import ohos.hiviewdfx.HiLogLabel;

import java.util.ArrayList;
import java.util.List;

/**
 * 主页面
 *
 * @author Kirky
 * @version 1.0
 * @date 2022/4/24
 */
public class MainSlice extends AbilitySlice {
    private static final HiLogLabel TAG = new HiLogLabel(HiLog.LOG_APP, 0x11, MainSlice.class.getSimpleName());
    private static final int INIT_FRACTION_INDEX = 0;
    private final Fraction[] fractions = new Fraction[]{new ScanFraction(this),
            new NewsFraction(this), new IndividualFraction(this)};

    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        DependentLayout dependentLayout = (DependentLayout) LayoutScatter.getInstance(this)
                .parse(ResourceTable.Layout_slice_main, null, false);
        setUIContent(dependentLayout);
        setStatusBar();
        initFractions();
        setFraction(INIT_FRACTION_INDEX);
        initNavigationMenu();
    }

    @Override
    protected void onActive() {

    }


    /**
     * 当能力片结束或被销毁时，销毁fractionManager中的fraction
     */
    @Override
    public void onStop() {
        super.onStop();
        FractionScheduler fractionScheduler = ((FractionAbility) getAbility()).getFractionManager()
                .startFractionScheduler();
        for (Fraction fraction : fractions) {
            fractionScheduler.remove(fraction);
        }
        fractionScheduler.submit();
    }

    private void setStatusBar() {
        getWindow().setStatusBarVisibility(WindowManager.LayoutConfig.MOD_APPLICATION_OVERLAY);
        getWindow().setStatusBarColor(ResourceHelper.getColorInt(getContext(),
                ResourceTable.Color_main_default, 0xFFFFFFFF));
        DisplayManager displayManager = DisplayManager.getInstance();
        Point realPoint = new Point();
        displayManager.getDefaultDisplay(getContext()).get().getRealSize(realPoint);
        Point point = new Point();
        displayManager.getDefaultDisplay(getContext()).get().getSize(point);
        int height = realPoint.getPointYToInt() - point.getPointYToInt();

        Component statusBar = new Component(getContext());
        statusBar.setLayoutConfig(new DirectionalLayout.LayoutConfig(
                DirectionalLayout.LayoutConfig.MATCH_PARENT, height
        ));
        DirectionalLayout layout = findComponentById(ResourceTable.Id_main_statusBar);
        layout.addComponent(statusBar);
    }

    /**
     * 将页面添加到fractionManager
     */
    private void initFractions() {
        FractionScheduler fractionScheduler = ((FractionAbility) getAbility()).getFractionManager()
                .startFractionScheduler();
        for (Fraction fraction : fractions) {
            fractionScheduler.add(ResourceTable.Id_main_fraction_container, fraction);
        }
        fractionScheduler.submit();
    }

    /**
     * 设置当前需要显示的fraction
     *
     * @param fractionIndex fraction index
     */
    private void setFraction(int fractionIndex) {
        FractionScheduler fractionScheduler = ((FractionAbility) getAbility()).getFractionManager()
                .startFractionScheduler();
        for (Fraction fraction : fractions) {
            fractionScheduler.hide(fraction);
        }
        fractionScheduler.show(fractions[fractionIndex]);
        fractionScheduler.submit();
    }

    /**
     * 初始化底部导航菜单，根据fraction的数量向导航菜单动态添加导航项，并高亮显示当前项。
     */
    private void initNavigationMenu() {
        DirectionalLayout navigationMenu = findComponentById(ResourceTable.Id_main_navigation_menu);

        List<NavigationItem> navigationItemList = getNavigationItemList();
        Color normalTextColor = ResourceHelper.getColor(this, ResourceTable.Color_navigation_unselected, Color.GRAY.getValue());
        Color selectedTextColor = ResourceHelper.getColor(this, ResourceTable.Color_navigation_selected, Color.GRAY.getValue());

        List<Image> navigationItemImageList = new ArrayList<>();
        List<Text> navigationItemTextList = new ArrayList<>();
        for (int i = 0; i < fractions.length; i++) {
            DirectionalLayout navigationItem = (DirectionalLayout) LayoutScatter.getInstance(getContext())
                    .parse(ResourceTable.Layout_layout_navigation_item, navigationMenu, false);
            Image navigationItemImage = navigationItem.findComponentById(ResourceTable.Id_navigation_item_image);
            Text navigationItemText = navigationItem.findComponentById(ResourceTable.Id_navigation_item_text);


            VectorElement selectedElement = new VectorElement(getContext(), navigationItemList.get(i).getSelectedImageId());
            VectorElement normalElement = new VectorElement(getContext(), navigationItemList.get(i).getNormalImageId());

            navigationItemImage.setBackground(i == INIT_FRACTION_INDEX ?
                    selectedElement : normalElement);
            navigationItemText.setTextColor(i == INIT_FRACTION_INDEX ?
                    selectedTextColor : normalTextColor);
            navigationItemText.setText(navigationItemList.get(i).getText());

            navigationItemImageList.add(navigationItemImage);
            navigationItemTextList.add(navigationItemText);

            final int currentNavigationIndex = i;
            navigationItem.setClickedListener((Component component) -> {
                for (int j = 0; j < navigationItemImageList.size(); j++) {

                    navigationItemImageList.get(j).setBackground(new VectorElement(getContext(), navigationItemList.get(j).getNormalImageId()));
                    navigationItemTextList.get(j).setTextColor(normalTextColor);
                }

                navigationItemImage.setBackground(
                        new VectorElement(getContext(),
                                navigationItemList.get(currentNavigationIndex).getSelectedImageId()));
                navigationItemText.setTextColor(selectedTextColor);
                setFraction(currentNavigationIndex);
            });
            navigationMenu.addComponent(navigationItem);
        }
    }

    /**
     * 获取底部导航栏item列表
     *
     * @return navigationItem list
     */
    private List<NavigationItem> getNavigationItemList() {
        List<NavigationItem> navigationItemList = new ArrayList<>();
//        识别页面
        navigationItemList.add(new NavigationItem(ResourceTable.Graphic_ic_scan_unselected,
                ResourceTable.Graphic_ic_scan_selected,
                ResourceHelper.getString(this, ResourceTable.String_main_fraction_scan, "", null)));
//        资讯页面
        navigationItemList.add(new NavigationItem(ResourceTable.Graphic_ic_news_unselected,
                ResourceTable.Graphic_ic_news_selected,
                ResourceHelper.getString(this, ResourceTable.String_main_fraction_news, "", null)));
//        我的页面
        navigationItemList.add(new NavigationItem(ResourceTable.Graphic_ic_mine,
                ResourceTable.Graphic_ic_mine_filled,
                ResourceHelper.getString(this, ResourceTable.String_main_fraction_individual, "", null)));

        return navigationItemList;
    }
}
